const { Pool } = require('pg');
require('dotenv').config();

// 创建数据库连接
const pool = new Pool({
  user: process.env.POSTGRES_USER || 'rwa_user',
  host: process.env.POSTGRES_HOST || 'localhost',
  database: 'postgres', // 连接到默认数据库来创建目标数据库
  password: process.env.POSTGRES_PASSWORD || 'rwa_password',
  port: process.env.POSTGRES_PORT || 5432,
});

async function initDatabase() {
  const client = await pool.connect();
  
  try {
    // 创建数据库（如果不存在）
    const dbName = process.env.POSTGRES_DB || 'rwa_contract';
    await client.query(`CREATE DATABASE "${dbName}"`);
    console.log(`✅ Database '${dbName}' created successfully`);
  } catch (error) {
    if (error.code === '42P04') {
      console.log(`ℹ️ Database '${process.env.POSTGRES_DB || 'rwa_contract'}' already exists`);
    } else {
      throw error;
    }
  } finally {
    client.release();
  }
  
  // 关闭连接池
  await pool.end();
}

// 运行初始化
initDatabase()
  .then(() => {
    console.log('✅ Database initialization completed');
    process.exit(0);
  })
  .catch((error) => {
    console.error('❌ Database initialization failed:', error);
    process.exit(1);
  });
